package com.andong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.andong.domain.entity.Student;
import com.andong.domain.pojo.Result;
import com.andong.domain.vo.CommentVO;
import com.andong.utils.BaseContext;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.andong.domain.entity.Comment;
import com.andong.service.CommentService;
import com.andong.mapper.CommentMapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.andong.utils.SystemConstant.*;

/**
* @author 王海云
* @description 针对表【comment(教练评论表)】的数据库操作Service实现
* @createDate 2024-01-13 14:36:59
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService{

    @Override
    public Result insert(Comment comment) {
        // 去掉评论的前后空格
        comment.setComment(comment.getComment().trim());
        // 检查是否是空字符串
        if (EMPTY_STRING.equals(comment.getComment())) {
            return Result.error(COMMENT_EMPTY);
        }
        // 1.检查请求是否正常
        String check = check(comment);
        if (!SUCCESS.equals(check)) {
            return Result.error(check);
        }
        saveOrUpdate(comment);
        return Result.success();
    }

    @Override
    public Result deleteById(Long id) {
        // 1.检查请求是否正常
        Long studentId = (Long) BaseContext.getCurrentIdAndIdentity().get(0);
        Comment comment = getById(id);
        if (!comment.getStudentId().equals(studentId)) {
            return Result.error(COMMENT_ERROR);
        }
        removeById(id);
        return Result.success();
    }

    @Override
    public List<CommentVO> queryList(Long id) {
        List<Comment> list = lambdaQuery()
                .eq(Comment::getCoachId, id)
                .orderByDesc(Comment::getUpdateTime)
                .list();
        return list.stream().map(record -> {
            CommentVO vo = new CommentVO();
            BeanUtil.copyProperties(record, vo);
            Long studentId = record.getStudentId();
            Student student = Db.lambdaQuery(Student.class)
                    .eq(Student::getId, studentId)
                    .one();
            vo.setStudentUsername(student.getUsername());
            vo.setStudentImg(student.getImage());
            return vo;
        }).toList();
    }

    private String check(Comment comment) {
        Long id = (Long) BaseContext.getCurrentIdAndIdentity().get(CURRENT_ID);
        Student student = Db.getById(id, Student.class);
        // 检查当前学员ID是否一致
        if (!id.equals(comment.getStudentId())) {
            return COMMENT_ERROR;
        }
        // 检查教练是否一致
        if (!student.getCoachId().equals(comment.getCoachId())) {
            return COMMENT_SELF_ERROR;
        }
        return SUCCESS;
    }
}




